home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 May: Tool Chest / Developer CD Series May 1996 (Tool Chest) (Apple Computer) (1996).iso / Sample Code / Snippets / Toolbox / AddResMenu7.1 / AddResMenu7.1.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-10  |  35.6 KB  |  914 lines  |  [TEXT/MPS ]

  1. /* MyAddResMenu */
  2. /* There is a minor bug in system 7.1 (oh no!) */
  3. /* AppendResMenu will only alphabatize 'FONT' resources, all others */
  4. /* will just be displayed in the order they appear in the resource map */
  5. /* of the resource fork. */
  6. /* This isn't harmful, it's just a little ugly. */
  7. /* Fixing it is pretty simple, just use the function in this sample */
  8. /* called MyAddResMenu */
  9. /* C.K. Haun */
  10. /* Apple DTS */
  11. /* Of course, Copyright 1991-1992, Apple Computer Inc. */
  12.  
  13. #include "AddResMenu7.1.h"
  14.  
  15. /* prototypes */
  16.  
  17. void InitalizeApp(void);
  18. void DoDiskEvents(long dinfo);                              /* hi word is error code, lo word is drive number */
  19. void DrawMain(WindowPtr drawIt);
  20. Boolean DoSelected(long val);
  21. void SizeMain(WindowPtr theWindow);
  22. void InitAEStuff(void);
  23. void DoHighLevel(EventRecord *AERecord);
  24. void DoDaCall(MenuHandle themenu, long theit);
  25. void DoDocumentClick(WindowPtr theWindow);
  26.  
  27. pascal OSErr AEOpenHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  28. pascal OSErr AEOpenDocHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  29. pascal OSErr AEPrintHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  30. pascal OSErr AEQuitHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  31.  
  32. void SampleHelpDialog(void);
  33.  
  34. WindowPtr AddNewWindow(short theID);
  35. short HasSelectionRange(DialogPeek inputDialog);
  36. Boolean IsEditKey(char theKey, short modifiers);
  37. void AddAResourceType(void);
  38. void MyAddResMenu(ResType theType, MenuHandle theMenu, short afterItem);
  39. pascal Boolean filterIt(DialogPtr inputDialog, EventRecord *myDialogEvent, short *theDialogItem);
  40. ControlHandle SnatchHandle(DialogPtr thebox, short theGetItem);
  41. void CleanUpMetaChars(Str255 theString);
  42. void NilProc(void);
  43. /* one external */
  44. extern void _DataInit();                                    /* this is the C initialization code */
  45.  
  46. /* globals */
  47. Boolean gQuit, gInBackground;
  48. unsigned long gMySleep;
  49. ProcessSerialNumber gOurSN;
  50. short gHelpItem;
  51. ModalFilterUPP gModalFilterUPP;
  52.  
  53. #ifdef powerc
  54.    QDGlobals    qd;
  55. #endif
  56.  
  57. #pragma segment Main
  58. main()
  59. {
  60.     EventRecord myEventRecord;
  61.     WindowPtr twindow;
  62.     short fHit;
  63.     windowCHandle tempWCH;
  64.     
  65.     UnloadSeg((Ptr)_DataInit);                              /* throw out setup code */
  66.     InitalizeApp();
  67.     UnloadSeg((Ptr)InitalizeApp);                           /* get rid of my initialization code */
  68.     do {
  69.         
  70.         WaitNextEvent(everyEvent, &myEventRecord, gMySleep, nil);
  71.         switch (myEventRecord.what) {
  72.             case nullEvent:
  73.                 /* no nul processing in this sample */
  74.                 break;
  75.             case updateEvt:
  76.                 /* always check to see if it's my window */
  77.                 /* this may not seem necessary under 7.0, where it's unlikely or impossible for */
  78.                 /* a DA to be in your layer, but there are others*/
  79.                 /* who can stick themselves into your window list, */
  80.                 /* BalloonWriter comes quickly to mind */
  81.                 
  82.                 if (((WindowPeek)myEventRecord.message)->windowKind == kMyDocumentWindow) {
  83.                     tempWCH = (windowCHandle)GetWRefCon((WindowPtr)myEventRecord.message);
  84.                     (ProcPtr)((*tempWCH)->drawMe)((WindowPtr)myEventRecord.message);
  85.                 }
  86.                 break;
  87.             case mouseDown:
  88.                 /* first see where the hit was */
  89.                 fHit = FindWindow(myEventRecord.where, &twindow);
  90.                 
  91.                 switch (fHit) {
  92.                     Rect limitRect;
  93.                     Str255 tempString;
  94.                     long back;
  95.                     case inDesk:                            /* if they hit in desk, then the process manager */
  96.                         break;                              /* will switch us out, we don't need to do anything */
  97.                     case inMenuBar:
  98.                         DoSelected(MenuSelect(myEventRecord.where));
  99.                         break;
  100.                         
  101.                     case inSysWindow:
  102.                         
  103.                         /* pass to the system */
  104.                         SystemClick(&myEventRecord, twindow);
  105.                         break;
  106.                     case inContent:
  107.                         
  108.                         /* Handle content and control clicks here */
  109.                         
  110.                         if (FrontWindow()) {                /* don't do this unless we have a window open, silly */
  111.                             windowCHandle clicker;
  112.                             if (((WindowPeek)twindow)->windowKind == kMyDocumentWindow) {
  113.                                 
  114.                                 clicker = (windowCHandle)GetWRefCon(twindow);
  115.                                 /* jump to the content function stored for this window */
  116.                                 HLock((Handle)clicker);     /* lock it down so things don't get stupid */
  117.                                 (ProcPtr)((*clicker)->clickMe)(twindow);
  118.                                 HUnlock((Handle)clicker);       /* all done */
  119.                             }
  120.                         }
  121.                         break;
  122.                     case inDrag:
  123.                         DragWindow(twindow, myEventRecord.where, &qd.screenBits.bounds);
  124.                         break;
  125.                     case inGrow:
  126.                         /* Call GrowWindow here if you have a grow box */
  127.                         SetPort(twindow);
  128.                         limitRect = qd.screenBits.bounds;
  129.                         limitRect.top = kMinHeight;
  130.                         GetWTitle(twindow, tempString);
  131.                         /* I'm not letting the user shrink the window so */
  132.                         /* small that the title is truncated */
  133.                         limitRect.left = StringWidth(tempString) + 120;
  134.                         back = GrowWindow(twindow, myEventRecord.where, &limitRect);
  135.                         
  136.                         if (back) {
  137.                             windowCHandle tempWCH = (windowCHandle)GetWRefCon(twindow);
  138.                             Rect sizeRect = ((WindowPtr)twindow)->portRect;
  139.                             InvalRect(&sizeRect);
  140.                             sizeRect.top = sizeRect.bottom - 16;
  141.                             sizeRect.left = sizeRect.right - 16;
  142.                             EraseRect(&sizeRect);
  143.                             InvalRect(&sizeRect);
  144.                             SizeWindow(twindow, back & 0xffff, back >> 16, true);
  145.                             (ProcPtr)((*tempWCH)->sizeMe)(twindow);
  146.                         }
  147.                         InvalRect(&twindow->portRect);
  148.                         
  149.                         break;
  150.                     case inGoAway:
  151.                         /* Click in Close box */
  152.                         if (TrackGoAway(twindow, myEventRecord.where)) {
  153.                             if (((WindowPeek)twindow)->windowKind == kMyDocumentWindow)
  154.                                 (ProcPtr)((*(windowCHandle)((WindowPeek)twindow)->refCon)->closeMe)(twindow);
  155.                         }
  156.                         break;
  157.                     case inZoomIn:
  158.                     case inZoomOut:
  159.                         if (TrackBox(twindow, myEventRecord.where, fHit)) {
  160.                             windowCHandle tempWCH = (windowCHandle)GetWRefCon(twindow);
  161.                             SetPort(twindow);
  162.                             
  163.                             ZoomWindow(twindow, fHit, true);
  164.                             InvalRect(&twindow->portRect);
  165.                             if (((WindowPeek)twindow)->windowKind == kMyDocumentWindow)
  166.                                 (ProcPtr)((*tempWCH)->sizeMe)(twindow);
  167.                         }
  168.                 }
  169.             case mouseUp:
  170.                 /* don't care */
  171.                 break;
  172.                 /* same action for key or auto key */
  173.             case keyDown:
  174.             case autoKey:
  175.                 if (myEventRecord.modifiers & cmdKey)
  176.                     DoSelected(MenuKey(myEventRecord.message & charCodeMask));
  177.                 break;
  178.             case keyUp:
  179.                 /* don't care */
  180.                 break;
  181.             case diskEvt:
  182.                 
  183.                 /* I don't do anything special for disk events, this just passes them */
  184.                 /* to a function that checks for an error on the mount */
  185.                 DoDiskEvents(myEventRecord.message);
  186.                 break;
  187.             case activateEvt:
  188.                 
  189.                 if (myEventRecord.modifiers & activeFlag) {
  190.                     if (((WindowPeek)myEventRecord.message)->windowKind == kMyDocumentWindow) {
  191.                         
  192.                         tempWCH = (windowCHandle)GetWRefCon((WindowPtr)myEventRecord.message);
  193.                         (ProcPtr)((*tempWCH)->drawMe)((WindowPtr)myEventRecord.message);
  194.                     }
  195.                 }
  196.                 break;
  197.             case networkEvt:
  198.                 /* don't care */
  199.                 break;
  200.             case driverEvt:
  201.                 /* don't care */
  202.                 break;
  203.             case app4Evt:
  204.                 switch ((myEventRecord.message >> 24) & 0x0FF) {        /* high byte of message */
  205.                     case suspendResumeMessage:              /* suspend/resume is also an activate/deactivate */
  206.                         gInBackground = (myEventRecord.message & kResumeMask) == 0;
  207.                         break;
  208.                 }
  209.                 break;
  210.             default:
  211.                 break;
  212.                 /* This dispatches high level events (AppleEvents, for example) */
  213.                 /* to our dispatch routine.This is NEW in the event loop for */
  214.                 /* System 7 */
  215.             case kHighLevelEvent:
  216.                 DoHighLevel(&myEventRecord);
  217.                 break;
  218.                 
  219.         }
  220.     }
  221.             while (gQuit != true);
  222.     
  223. }
  224.  
  225. /* DoDaCall opens the requested DA.It's here as a seperate routine if you'd */
  226. /* like to perform some action or just know when a DA is opened in your */
  227. /* layer.Can be handy to track memory problems when a DA is opened */
  228. /* with an Option-open */
  229. void DoDaCall(MenuHandle themenu, long theit)
  230. {
  231.     long qq;
  232.     char DAname[255];
  233.     GetMenuItemText(themenu, theit, &DAname);
  234.     qq = OpenDeskAcc(DAname);
  235. }
  236.  
  237. /* end DoDaCall */
  238.  
  239. /* DoDiskEvents just checks the error code from the disk mount, */
  240. /* and puts up the 'Format' dialog (through DIBadMount) if need be */
  241. /* You can do much more here if you care about what disks are */
  242. /* in the drive */
  243. void DoDiskEvents(long dinfo)                               /* hi word is error code, lo word is drive number */
  244. {
  245.     short hival, loval, tommy;
  246.     Point fredpoint =  {
  247.         40, 40
  248.     };
  249.     hival = HiWord(dinfo);
  250.     loval = LoWord(dinfo);
  251.     if (hival != noErr)                                     /* something happened */ {
  252.         tommy = DIBadMount(fredpoint, dinfo);
  253.     }
  254. }
  255.  
  256. /* draws my window.Pretty simple */
  257. void DrawMain(WindowPtr drawIt)
  258. {
  259.     RgnHandle tempRgn;
  260.     Rect scratchRect;
  261.     BeginUpdate(drawIt);
  262.     SetPort(drawIt);
  263.     scratchRect = drawIt->portRect;
  264.     scratchRect.top = scratchRect.bottom - 15;
  265.     scratchRect.left = scratchRect.right - 15;
  266.     tempRgn = NewRgn();
  267.     GetClip(tempRgn);
  268.     ClipRect(&scratchRect);
  269.     DrawGrowIcon(drawIt);
  270.     SetClip(tempRgn);
  271.     DisposeRgn(tempRgn);
  272.     
  273.     EndUpdate(drawIt);
  274. }
  275.  
  276. /* my menu action taker.It returns a Boolean which I usually ignore, but it */
  277. /* mught be handy someday */
  278. /* I usually use it in an application to determine if a keystroke was accepted */
  279. /* by a menu or whether it should be passed along to any other key acceptors */
  280. Boolean DoSelected(long val)
  281. {
  282.     short loval, hival;
  283.     Boolean returnVal = false;
  284.     loval = LoWord(val);
  285.     hival = HiWord(val);
  286.     
  287.     switch (hival) {                                        /* switch off the menu number selected */
  288.         case kAppleMenu:                                    /* Apple menu */
  289.             if (loval != 1) {                               /* if this was not About, it's a DA */
  290.                 DoDaCall(GetMenuHandle(kAppleMenu), loval);
  291.             } else {
  292.                 Alert(kAboutBox, nil);                      /* do about box */
  293.             }
  294.             returnVal = true;
  295.             break;
  296.             
  297.         case kFileMenu:                                     /* File menu */
  298.             switch (loval) {
  299.                 
  300.                 case kQuitItem:
  301.                     gQuit = true;                           /* onlyitem */
  302.                     returnVal = true;
  303.                     break;
  304.                 default:
  305.                     break;
  306.             }
  307.             break;
  308.             
  309.         case kEditMenu:
  310.             /* edit menu junk */
  311.             /* don't care */
  312.             
  313.             switch (loval) {
  314.             default:
  315.                 break;
  316.             }
  317.             break;
  318.             
  319.         case kToolsMenu:
  320.             /* add all your test stuff here */
  321.             
  322.             switch (loval) {
  323.                 case kTestMenuChooseType:
  324.                     AddAResourceType();
  325.                     break;
  326.                 default:
  327.                     break;
  328.             }
  329.             break;
  330.             
  331.         case kHMHelpMenuID:                                 /* Defined in Balloons.h */
  332.             /* I only care about this item.If anything else is returned here, I don't know what */
  333.             /* it is, so I leave it alone.Remember, the Help Manager chapter says that */
  334.             /* Apple reserves the right to add and change things in the Help menu */
  335.             if (loval == gHelpItem)
  336.                 SampleHelpDialog();
  337.             break;
  338.             
  339.     }
  340.     HiliteMenu(0);
  341.     return(returnVal);
  342. }
  343.  
  344. void DoDocumentClick(WindowPtr theWindow)
  345. {
  346.     
  347. }
  348.  
  349. void InitAEStuff(void)
  350. {    
  351.     OSErr aevtErr = noErr;
  352.     long aLong = 0;
  353.     Boolean gHasAppleEvents = false;
  354.     /* Check this machine for AppleEvents.  If they are not here (ie not 7.0)
  355.     *   then we exit */
  356.     gHasAppleEvents = (Gestalt(gestaltAppleEventsAttr, &aLong) == noErr);
  357.     /* The following series of calls installs all our AppleEvent Handlers.
  358.     *   These handlers are added to the application event handler list that 
  359.     *   the AppleEvent manager maintains.  So, whenever an AppleEvent happens
  360.     *   and we call AEProcessEvent, the AppleEvent manager will check our
  361.     *   list of handlers and dispatch to it if there is one.
  362.     */
  363.     if (gHasAppleEvents) {
  364.          aevtErr = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, 
  365.              NewAEEventHandlerProc(AEOpenHandler),0, false);
  366.              if (aevtErr)  ExitToShell();
  367.  
  368.          aevtErr = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, 
  369.              NewAEEventHandlerProc(AEOpenDocHandler),0, false);
  370.              if (aevtErr)  ExitToShell();
  371.  
  372.          aevtErr = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, 
  373.              NewAEEventHandlerProc(AEQuitHandler), 0, false);
  374.              if (aevtErr)  ExitToShell();
  375.  
  376.          aevtErr = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments, 
  377.              NewAEEventHandlerProc(AEPrintHandler),0, false);
  378.              if (aevtErr)  ExitToShell();
  379.          
  380.        } 
  381.     else ExitToShell();
  382.     
  383. }
  384. /* end InitAEStuff */
  385.  
  386. /* I'm not doing error handling in this sample for clarities sake, you should. Hah, */
  387. /* easy for me to say, huh? */
  388. void DoHighLevel(EventRecord *AERecord)
  389. {
  390.     OSErr myErr;
  391.     myErr = AEProcessAppleEvent(AERecord);
  392.     
  393. }
  394.  
  395. /* end DoHighLevel */
  396.  
  397. /* This is the standard Open Application event.*/
  398. pascal OSErr AEOpenHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  399. {
  400.     WindowPtr myWindow;
  401.  
  402. #pragma unused (messagein,reply,refIn)
  403.     /* we of course don't do anything here in this simple app */
  404.     /* except open our window */
  405.     myWindow = AddNewWindow(kDocWindowResID);
  406.     
  407.     return(noErr);
  408. }
  409.  
  410. /* end AEOpenHandler */
  411.  
  412. /* Open Doc, opens our documents.Remember, this can happen at application start AND */
  413. /* anytime else.If your app is up and running and the user goes to the desktop, hilites one */
  414. /* of your files, and double-clicks or selects Open from the finder File menu this event */
  415. /* handler will get called. Which means you don't do any initialization of globals here, or */
  416. /* anything else except open then doc.*/
  417. /* SO-- Do NOT assume that you are at app start time in this */
  418. /* routine, or bad things will surely happen to you. */
  419.  
  420. pascal OSErr AEOpenDocHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  421. {
  422. #pragma unused (messagein,refIn,reply)
  423.     /* we of course don't do anything here */
  424.     return(errAEEventNotHandled);                           /* we have no docs, so no odoc events should come to us */
  425. }
  426.  
  427. pascal OSErr AEPrintHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  428. {                                                           /* no printing handler in yet, so we'll ignore this */
  429.     /* the operation is functionally identical to the ODOC event, with the additon */
  430.     /* of calling your print routine.*/
  431. #pragma unused (messagein,refIn,reply)
  432.     /* we of course don't do anything here */
  433.     return(errAEEventNotHandled);                           /* we have no docs, so no pdoc events should come to us */
  434. }
  435.  
  436. /* Standard Quit event handler, to handle a Quit event from the Finder, for example.*/
  437. /* ••••• DO NOT CALL EXITTOSHELL HERE ••••• or you will never have a happy life.*/
  438. /* OK, it's a few months after I wrote that comment, and I've seen a lot of code */
  439. /* come through DTS that calls ExitToShell from quit handlers.Let me explain... */
  440. /* When an AppleEvent Handler is called (like this quit handler) you are ALMOST */
  441. /* 100% in your application world.A5 is right, you can call any toolbox function, */
  442. /* you can call your own routines, everything _seems_ like you are in complete*/
  443. /* control.Well, almost but not quite.The routine has been dispatch to from the */
  444. /* AppleEvent Manager's space, so you _must_ return to that at some point! */
  445. /* Which is why you can't call ETS from here.When you call ExitToShell from an */
  446. /* AE Handler, the most likely thing that happens is the FInder quits, and your*/
  447. /* application keeps running.Which ain't what you want, y'know? */
  448. /* so, DON'T CALL EXITTOSHELL FROM AN APPLEEVENT HANDLER!!!!!!!!!!!!!! */
  449. pascal OSErr AEQuitHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  450. {
  451. #pragma unused (messagein,refIn,reply)
  452.     gQuit = true;
  453.     return(noErr);
  454. }
  455.  
  456. /* This is my sample help dialog.Does not do anything, expand as you need */
  457. void SampleHelpDialog(void)
  458. {
  459.     DialogPtr tdial = GetNewDialog(kSampHelp, nil, (WindowPtr)-1);
  460.     short itemhit = 0;
  461.     while (itemhit != 1) {
  462.         ModalDialog(nil, &itemhit);
  463.     }
  464.     DisposeDialog(tdial);
  465. }
  466.  
  467. WindowPtr AddNewWindow(short theID)
  468. {
  469.     windowCHandle setControls;
  470.     WindowPtr tempWP;
  471.     short cnt = 0;
  472.     tempWP = GetNewWindow(theID, 0, (WindowPtr)-1);         /* get a new window */
  473.     ((WindowPeek)tempWP)->windowKind = kMyDocumentWindow;       /* mark it as my document window */
  474.     setControls = (windowCHandle)NewHandleClear(sizeof(windowControl));     /* add our control structure to it */
  475.     SetWRefCon(tempWP, (long)setControls);                  /* stop stuffing refCon directly <ckh 1.0.3> */
  476.     HLock((Handle)setControls);                             /* lock it down while we fill it*/
  477.     
  478.     /* add pointers to our procedures for drawing, saving, and closing */
  479.     /* This way, all I need is one dispatch point for drawing, closing */
  480.     /* or whatever, I don't have to case off the window kind to go to the*/
  481.     /* correct routine.Kinda like object-oriented programming, but I won't */
  482.     /* admit that. */
  483.     (*setControls)->drawMe = (ProcPtr)DrawMain;
  484.     (*setControls)->clickMe = (ProcPtr)DoDocumentClick;
  485.     (*setControls)->sizeMe = (ProcPtr)SizeMain;
  486.     (*setControls)->generalData = NewHandle(0);
  487.     return(tempWP);
  488. }
  489.  
  490. void SizeMain(WindowPtr theWindow)
  491. {
  492.     WindowPtr tempWP;
  493.     GetPort(&tempWP);
  494.     InvalRect(&theWindow->portRect);
  495.     SetPort(tempWP);
  496. }
  497.  
  498. void NilProc(void)
  499. {
  500.     
  501. }
  502.  
  503. /* AddAResourceType asks for the resource type to add to the menu */
  504. /* it preflights to see if at least one exists, then passes of to MyAddResMenu */
  505. void AddAResourceType(void)
  506. {
  507.     Rect tempRect;
  508.     short tempItem;
  509.     Handle tempHandle;
  510.     Str15 myStr;
  511.     ResType theType;
  512.     short hitItem;
  513.     DialogPtr myDialog = GetNewDialog(kResTypeDialog, nil, (WindowPtr)-1);
  514.     
  515.     /* New System 7 dialog manager calls, see tech note #304 */
  516.     /* interface to these calls is in AddResMenu7.1.h */
  517.     SetDialogDefaultItem(myDialog, ok);
  518.     SetDialogCancelItem(myDialog, cancel);
  519.     SetDialogTracksCursor(myDialog, true);
  520.     
  521.     do {
  522.         ModalDialog(gModalFilterUPP, &hitItem);
  523.     }
  524.             while (hitItem != ok && hitItem != cancel);
  525.     
  526.     if (hitItem == ok) {
  527.         
  528.         /* get the type and hammer it */
  529.         GetDialogItem(myDialog, kResTypeEditLine, &tempItem, &tempHandle, &tempRect);
  530.         GetDialogItemText(tempHandle, myStr);
  531.         
  532.         /* make sure there are 4 characters here, please */
  533.         if (myStr[0] == 4) {
  534.             BlockMove((Ptr)&myStr[1], (Ptr)&theType, sizeof(theType));
  535.             /* reality check to see if there are any of these at this time */
  536.             tempItem = Count1Resources(theType);
  537.             if (tempItem) {
  538.                 /* clear the menu out before I add new things*/
  539.                 tempItem = CountMItems(GetMenuHandle(kToolsMenu));
  540.                 
  541.                 /* I want to add below the dividing line */
  542.                 tempItem -= kTestMenuDivider;
  543.                 while (tempItem) {
  544.                     DeleteMenuItem(GetMenuHandle(kToolsMenu), kTestMenuDivider + 1);
  545.                     
  546.                     tempItem--;
  547.                 }
  548.                 
  549.                 /* call my routine */
  550.                 MyAddResMenu(theType, GetMenuHandle(kToolsMenu), kTestMenuDivider);
  551.             } else {
  552.                 /* yell because there are none of that type around */
  553.                 ParamText(myStr, "", "", "");
  554.                 CautionAlert(kNoneOfThatType, nil);
  555.             }
  556.         }
  557.     }
  558.     DisposeDialog(myDialog);
  559.     
  560. }
  561.  
  562. /* MyAddResMenu does, basically, what AddResmenu does, it does an */
  563. /* "insert sort" (one of the Comp. Sci. types around here told me to call it that) */
  564. /* of the names of the resources.It uses IUCompString for */
  565. /* International Reasons (KFJC 89.7, 12-3 Sundays) */
  566. /* The only thing it really does differently is includes items that don't have */
  567. /* names by including the 'unnamedX' string. */
  568. /* Also notice that, since I'm using InsertMenuItem I have to parse the*/
  569. /* name string and take out any menu manager meta-characters before I insert things */
  570. /* so I don't get strange command keys from a name like "Alert/Warning 1" */
  571.  
  572. void MyAddResMenu(ResType theType, MenuHandle theMenu, short afterItem)
  573. {
  574.     short originalCount = afterItem;
  575.     short resourceCount = Count1Resources(theType);
  576.     short index = 1;
  577.     short unnamedCount = 0;
  578.     short qq;
  579.     ResType theIndexType;
  580.     short theID;
  581.     Str255 theName;
  582.     Str32 unusedWord;
  583.     Str255 tempString;
  584.     Handle tempHandle;
  585.     Boolean oldResLoad = *((Boolean *)0xA5E);
  586.     Boolean addedIt = false;
  587.     
  588.     GetIndString(unusedWord, kGenStrings, kUnnamedString);
  589.     SetResLoad(false);                                      /* don't want to load the resources */
  590.     do {
  591.         tempHandle = Get1IndResource(theType, index);
  592.         theName[0] = 0;
  593.         GetResInfo(tempHandle, &theID, &theIndexType, &theName);
  594.         /* Check the name, if no name tell it so... */
  595.         if (theName[0] == 0) {
  596.             BlockMove((Ptr)&unusedWord, (Ptr)&theName, unusedWord[0] + 1);
  597.             NumToString((long)unnamedCount, tempString);
  598.             if ((theName[0] + tempString[0]) < 254) {
  599.                 BlockMove((Ptr)&tempString[1], (Ptr)(&theName[1] + theName[0]), tempString[0]);
  600.                 theName[0] += tempString[0];
  601.             }
  602.             unnamedCount++;
  603.         }
  604.         CleanUpMetaChars(theName);
  605.         /* here's where you sort in the menu items */
  606.         /* it goes roughly like.... */
  607.         for (qq = afterItem + 1; qq < CountMItems(theMenu) + 1; qq++) {
  608.             GetMenuItemText(theMenu, qq, &tempString);
  609.             if (IUCompString(theName, tempString) == -1) {
  610.                 /* new string is less than an existing name */
  611.                 /* so insert it before it */
  612.                 InsertMenuItem(theMenu, theName, qq - 1);
  613.                 addedIt = true;
  614.                 break;                                      /* leave the 'for' loop */
  615.             }
  616.         }
  617.         /* If it didn't sort in, just add it to the end of the menu */
  618.         if (!addedIt)
  619.             InsertMenuItem(theMenu, theName, CountMItems(theMenu) + 1);
  620.         addedIt = false;
  621.         index++;
  622.     }
  623.             while (index <= resourceCount);
  624.     SetResLoad(oldResLoad);
  625. }
  626.  
  627. /* Some dialog filtering things */
  628. /* TabRetEsc toggles the cancel or OK button for keystrokes, and */
  629. /* treats a Tab press as selecting the whole edit line contents */
  630.  
  631. Boolean TabRetEsc(DialogPtr inputDialog, EventRecord *myDialogEvent, short *theDialogItem)
  632. {
  633.     Boolean returnValue = false;
  634.     long tilticks;
  635.     WindowPtr tempWindowPtr;
  636.     char theKey = myDialogEvent->message &charCodeMask;
  637.     GetPort(&tempWindowPtr);
  638.     SetPort(inputDialog);
  639.     switch (theKey) {
  640.         case kReturnKey:
  641.         case kEnterKey:                                     /* enter key */
  642.             /* This filters for Return or Enter as item 1, and Esc as item 2 */
  643.             *theDialogItem = ok;                            /* change whatever the current item is to the OK item */
  644.             /* now we need to invert the button */
  645.             HiliteControl(SnatchHandle(inputDialog, ok), inButton);
  646.             Delay(8, &tilticks);                            /* wait about 8 ticks so they can see it */
  647.             HiliteControl(SnatchHandle(inputDialog, ok), false);
  648.             returnValue = true;
  649.             break;
  650.             /* This filters the escape key as the same as item 2 (the canx button, usually ) */
  651.         case kEscKey:
  652.             *theDialogItem = cancel;
  653.             HiliteControl(SnatchHandle(inputDialog, cancel), inButton);
  654.             Delay(8, &tilticks);                            /* wait about 8 ticks so they can see it */
  655.             HiliteControl(SnatchHandle(inputDialog, cancel), false);
  656.             returnValue = true;
  657.             break;
  658.         case kTabKey:
  659.             /* I'm filtering the tab key here so a tab selects all the */
  660.             /* text in the edit line, as a convinience */
  661.             SelectDialogItemText(inputDialog, kResTypeEditLine, 0, 5);
  662.             returnValue = true;                             /* don't allow edit line swaps */
  663.             break;
  664.     }
  665.     SetPort(tempWindowPtr);
  666.     
  667.     return(returnValue);
  668.     
  669. }
  670.  
  671. /* Main dialog filter */
  672. pascal Boolean filterIt(DialogPtr inputDialog, EventRecord *myDialogEvent, short *theDialogItem)
  673. {
  674.     
  675.     Boolean returnVal = false;
  676.     ModalFilterUPP theModalProc;
  677.     char theKey;
  678.     Rect tempRect;
  679.     short tempItem;
  680.     Handle tempHandle;
  681.     char tempKey;
  682.     Str255 myStr;
  683.     long offset;
  684.     short selection;
  685.     long scrapLen;
  686.     short resultLen;
  687.     Boolean wasAKey = false;
  688.     if (myDialogEvent->what == updateEvt && myDialogEvent->message != inputDialog) {
  689.         /* May be a pending update event for another window, handle it so */
  690.         /* other layers get time */
  691.         windowCHandle tempWCH;
  692.         WindowPtr theWindow = (WindowPtr)myDialogEvent->message;
  693.         /* draw my window if it's really mine */
  694.         if (((WindowPeek)theWindow)->windowKind == kMyDocumentWindow) {
  695.             tempWCH = (windowCHandle)GetWRefCon(theWindow);
  696.             (ProcPtr)((*tempWCH)->drawMe)((WindowPtr)theWindow);
  697.             
  698.             *theDialogItem = 0;
  699.             returnVal = true;
  700.         }
  701.     } else {
  702.         wasAKey = (myDialogEvent->what == keyDown) || (myDialogEvent->what == autoKey);
  703.         
  704.         if ((wasAKey)) {
  705.             /* first check on the Big Three, tab, return, and escape */
  706.             if (!(returnVal = TabRetEsc(inputDialog, myDialogEvent, theDialogItem))) {
  707.                 
  708.                 /* not one of those, see if this keystroke will fit */
  709.                 /* in the edit line (restricted to 4 characters for a ResType) */
  710.                 
  711.                 /* Here I'm seeing if anything is selected, and getting the length */
  712.                 /* of the desk scrap in case the user presses */
  713.                 /* Copy or Paste keys */
  714.                 
  715.                 selection = HasSelectionRange((DialogPeek)inputDialog);
  716.                 scrapLen = GetScrap(nil, 'TEXT', &offset);
  717.                 
  718.                 GetDialogItem(inputDialog, kResTypeEditLine, &tempItem, &tempHandle, &tempRect);
  719.                 GetDialogItemText(tempHandle, myStr);
  720.                 
  721.                 /* calculate the result of adding the scrap to the current record.We use */
  722.                 /* this in a few places here */
  723.                 resultLen = myStr[0] + (scrapLen - selection);
  724.                 
  725.                 theKey = myDialogEvent->message & charCodeMask;
  726.                 tempKey = theKey;
  727.                 if (tempKey >= 0x61 && tempKey <= 0x7a)
  728.                     tempKey -= 0x20;
  729.                 
  730.                 if (myStr[0] > 3) {                         /* over 4, see what it is */
  731.                     
  732.                     if (IsEditKey(theKey, myDialogEvent->modifiers)) {
  733.                         /* it was an editing key, but it MAY be a command-V. */
  734.                         /* If it's a command-V then we won't allow it UNLESS */
  735.                         /* there is a slection range AND the new data won't overrun things */
  736.                         if ((tempKey == 'V') && (myDialogEvent->modifiers & cmdKey)) {
  737.                             
  738.                             /* this was a paste.check selection range and scrap len*/
  739.                             if (resultLen < 4) {
  740.                                 returnVal = false;          /* net result is4 or less */
  741.                             } else {
  742.                                 SysBeep(1);
  743.                                 returnVal = true;
  744.                             }
  745.                         } else {
  746.                             returnVal = false;              /* don't filter out editing keys */
  747.                         }
  748.                     } else {
  749.                         /* One more check (this can get complicated, huh?) */
  750.                         /* We now look to see if there is a selection range.If there */
  751.                         /* is a range of 1 or more characters, then the one character they are entering */
  752.                         /* now will replace that, and we'll end up with _less_ than 4 (or equal) */
  753.                         /* to do this, we have to get the TERecord out of the dialog.*/
  754.                         /* I'm going to do this in a seperate function */
  755.                         if (selection == nil) {
  756.                             SysBeep(1);                     /* complain a little */
  757.                             returnVal = true;               /* tell the dialog manager that we handled this already and */
  758.                             /* it doesn't have to, so the keystroke will _not_ get */
  759.                             /* added to the edit line */
  760.                         }
  761.                     }
  762.                 } else {
  763.                     /* even if we're less than 4 currently, a Command-V (paste) could put us over */
  764.                     /* so check it out */
  765.                     
  766.                     if ((tempKey == 'V') && (myDialogEvent->modifiers & cmdKey)) {
  767.                         
  768.                         /* Gettting the scrap with a nil handle, which does not give us data, just */
  769.                         /* returns the size */
  770.                         if (resultLen > 3) {
  771.                             SysBeep(1);                     /* complain a little */
  772.                             returnVal = true;               /* tell the dialog manager that we handled this already and */
  773.                             
  774.                         }
  775.                     }
  776.                 }
  777.             }
  778.         }
  779.     }
  780.     if (!returnVal) {
  781.         
  782.         OSErr myErr = GetStdFilterProc(&theModalProc);
  783.         if (myErr == noErr)
  784.             returnVal = CallModalFilterProc(theModalProc, inputDialog, myDialogEvent, theDialogItem);
  785.     }
  786.     return(returnVal);
  787. }
  788.  
  789. short HasSelectionRange(DialogPeek inputDialog)
  790. {
  791.     TEHandle theTERecord = inputDialog->textH;
  792.     short returnVal = (*theTERecord)->selEnd -(*theTERecord)->selStart;
  793.     
  794.     return(returnVal);
  795. }
  796.  
  797. /* end HasSelectionRange */
  798.  
  799. /* a little utility to see if the current key is an edit-type key */
  800. Boolean IsEditKey(char theKey, short modifiers)
  801. {
  802.     register qq;
  803.     Boolean returnVal = false;
  804.     char editChars[] =  {
  805.         kLeftArrow, kUpArrow, kRightArrow, kDownArrow, kBackSpace, kEscKey
  806.     };
  807.     char commandEdits[] =  {
  808.         'C', 'V', 'P'
  809.     };
  810.     for (qq = 0; qq < sizeof(editChars) / sizeof(char); qq++) {
  811.         if (theKey == editChars[qq])
  812.             returnVal = true;
  813.     }
  814.     if (returnVal != true && (modifiers & cmdKey)) {
  815.         /* check for XCP */
  816.         /* Do you want me to use 'toupper()'?What! And link in all of StdLib! aggggg */
  817.         if (theKey >= 0x61 && theKey <= 0x7a)
  818.             theKey -= 0x20;
  819.         for (qq = 0; qq < sizeof(commandEdits) / sizeof(char); qq++) {
  820.             if (theKey == commandEdits[qq])
  821.                 returnVal = true;
  822.         }
  823.     }
  824.     return(returnVal);
  825. }
  826.  
  827. /* end IsEditKey */
  828.  
  829. /* Gets the ControlHandle for the item you want in the dialog box thebox.*/
  830. /* Handy for setting checkboxes and radio buttons */
  831. /* This is the _most_ copied routine from this file */
  832. ControlHandle SnatchHandle(DialogPtr thebox, short theGetItem)
  833. {
  834.     short itemtype;
  835.     Rect itemrect;
  836.     Handle thandle;
  837.     
  838.     GetDialogItem(thebox, theGetItem, &itemtype, &thandle, &itemrect);
  839.     return((ControlHandle)thandle);
  840. }
  841.  
  842. /* end SnatchHandle */
  843.  
  844. void CleanUpMetaChars(Str255 theString)
  845. {
  846.     char metaKeys[] =  {
  847.         ';', '^', '!', '<', '/', '('
  848.     };
  849.     register qq, ii;
  850.     
  851.     qq = theString[0];
  852.     while (qq) {
  853.         for (ii = 0; ii < sizeof(metaKeys) / sizeof(char); ii++) {
  854.             if (theString[qq] == metaKeys[ii])
  855.                 theString[qq] = '•';                         /* replace with a Spot */
  856.         }
  857.         qq--;
  858.     }
  859. }
  860.  
  861.  
  862. #pragma segment Initialize
  863. void InitalizeApp(void)
  864. {
  865.     Handle myMenu;
  866.     MenuHandle helpHandle, appleMenuHandle;
  867.     StringHandle helpString;
  868.     short count;
  869.     long vers;
  870.     MaxApplZone();
  871.     InitGraf((Ptr)&qd.thePort);
  872.     InitFonts();
  873.     InitWindows();
  874.     InitMenus();
  875.     TEInit();
  876.     InitDialogs(nil);
  877.     InitCursor();
  878.     /* Check system version */
  879.     Gestalt(gestaltSystemVersion, &vers);
  880.     vers = (vers >> 8) & 0xf;                               /* shift result over and mask out major version number */
  881.     if (vers < 7) {
  882.         StopAlert(kBadSystem, nil);
  883.         ExitToShell();
  884.     }
  885.     InitAEStuff();
  886.     
  887.     /* set up the UPP for our dialog filter proc */
  888.     gModalFilterUPP = NewModalFilterProc(filterIt);
  889.   
  890.     /* set up my menu junk */
  891.     myMenu = GetNewMBar(kMBarID);
  892.     SetMenuBar(myMenu);
  893.     appleMenuHandle = GetMenuHandle(kAppleMenu);
  894.     AppendResMenu(appleMenuHandle, 'DRVR');
  895.     
  896.     /* now install my Help menu item in the Help Manager's menu */
  897.     HMGetHelpMenuHandle(&helpHandle);                       /* Get the Hlpe menu handle */
  898.     count = CountMItems(helpHandle);                        /* How many items are there? */
  899.     helpString = GetString(kHelpString);                    /* get my help string */
  900.     DetachResource(helpString);                             /* detach it */
  901.     HNoPurge(helpString);
  902.     MoveHHi((Handle)helpString);
  903.     HLock((Handle)helpString);
  904.     InsertMenuItem(helpHandle, (Ptr)*helpString, count + 1);       /* insert my item in the Help menu */
  905.     gHelpItem = CountMItems(helpHandle);                    /* The number of the item */
  906.     
  907.     DrawMenuBar();
  908.     GetCurrentProcess(&gOurSN);                             /* Get our process serial number for later use, if needed */
  909.     
  910. }
  911.  
  912.  
  913. #pragma segment Main
  914.